﻿@using PMS.Web.Models.ScheduleTasks
@{
    Layout = "_AdminHomeLayout";
    int ModuleId = (int)ViewBag.ModuleId;
}
@model ScheduleTaskModel
@section CssStyles{
    <style type="text/css">
        tbody .layui-table-cell {
            height: 90px !important;
            line-height: 90px;
            white-space: normal;
            /*设置为伸缩容器*/
            display: -webkit-box;
            display: -moz-box;
            display: -ms-flexbox;
            display: -webkit-flex;
            display: flex;
            /*垂直居中*/
            -webkit-box-align: center; /*旧版本*/
            -moz-box-align: center; /*旧版本*/
            -ms-flex-align: center; /*混合版本*/
            -webkit-align-items: center; /*新版本*/
            align-items: center; /*新版本*/
        }
    </style>
}
<div class="layui-card">
    <div class="layui-card-body">
        <table id="pms-table" lay-filter="pms-table"></table>
    </div>
</div>

<div id="taskGroupNames" class="layui-hide">
    @foreach (var name in Html.GetEnumSelectList(typeof(ScheduleJobGroup)))
    {
        <div data-grpname="@name.Text" data-grpdesc="@(name.Value.ToEnum<ScheduleJobGroup>().GetDescription(true))"></div>
    }
</div>
<input type="text" id="gridPageSize" value="@Model.AvailablePageSizes" class="layui-hide" />
<script type="text/html" id="taskStatusTpl">
    {{#  if(d.Status === 0 || d.Status === 2){ }}
    <button type="button" class="tag-item tag-item-normal layui-btn layui-btn-primary layui-btn-xs">运行中</button>
    {{#  } else if(d.Status === 1){ }}
    <button type="button" class="tag-item tag-item-warm layui-btn layui-btn-primary layui-btn-xs">暂停</button>
    {{#  } else if(d.Status === 3){ }}
    <button type="button" class="tag-item tag-item-danger layui-btn layui-btn-primary layui-btn-xs">错误</button>
    {{#  } else { }}
    <button type="button" class="tag-item tag-item-danger layui-btn layui-btn-primary layui-btn-xs">停止</button>
    {{#  } }}
</script>
@await Component.InvokeAsync("ModuleButtonTemplet", new { moduleId = ModuleId, position = ModuleButtonGroup.HeadButtonsGroup })
@await Component.InvokeAsync("ModuleButtonTemplet", new { moduleId = ModuleId, position = ModuleButtonGroup.RecordButtonsGroup })

<script type="text/html" id="pmsRecordMoreTpl">
    <button class="pear-btn pear-btn-sm" id="dropdownmore_{{d.Id}}">
        <span>操作</span>
        <i class="layui-icon layui-icon-triangle-d"></i>
    </button>
</script>
<!-- 下拉内容自定义模板 -->
<script id="dropdownItemTpl" type="text/html">
    {{# layui.each(d.dropdownBtns, function(index, item){ }}
    <div class="layu-menu-item {{item.txtClass}}" lay-event="{{item.event}}" data-moduleid="{{item.moduleId}}" data-buttonid="{{item.buttonId}}">
        <a href="javascript:;" class="{{item.txtClass}}">
            {{#  if(item.layIcon !== "none"){ }}
            <i class="{{ item.layIcon }}"></i>&nbsp;
            {{#  } }}
            <span>{{item.txt}}</span>
        </a>
    </div>
    {{#  }); }}
</script>
<script type="text/html" id="datetimeTpl">
    <div style="width: 100%;">
        <div class="layui-row" style="width:100%; line-height: 25px;">
            <div class="layui-col-md5">@Model.DisplayName(m => m.LastStartTime)</div>
            <div class="layui-col-md7">{{d.LastStartTime}}</div>
        </div>
        <div class="layui-row" style="width:100%; line-height: 25px;">
            <div class="layui-col-md5">@Model.DisplayName(m => m.LastStopTime)</div>
            <div class="layui-col-md7">{{d.LastStopTime}}</div>
        </div>
        <div class="layui-row" style="width:100%; line-height: 25px;">
            <div class="layui-col-md5">@Model.DisplayName(m => m.LastSuccessTime)</div>
            <div class="layui-col-md7">{{d.LastSuccessTime}}</div>
        </div>
    </div>
</script>
@section Scripts{
    <script type="text/javascript">
        layui.use(['table', 'jquery', 'layuidropdown', 'http', 'loading', 'popup', 'lodash'], function () {
            let table = layui.table;
            let $ = layui.jquery;
            let dropdown = layui.layuidropdown;
            let http = layui.http;
            let loading = layui.loading;
            let popup = layui.popup;
            let lodash = layui.lodash;
            let availabePageSize = PMSUtils.parseToIntegerArray($("#gridPageSize").val());
            let taskGroupNames = [];
            $("#taskGroupNames>div").each(function () {
                taskGroupNames.push({
                    grpname: $(this).data("grpname"),
                    grpdesc: $(this).data("grpdesc")
                });
            });
            table.render({
                elem: '#pms-table',
                url: backendwebapiConfig.loadscheduletaskBypage,
                request: {
                    pageName: '@Model.NameOf(p => p.Page)', //页码的参数名称，默认：page
                    limitName: '@Model.NameOf(p => p.PageSize)' //每页数据量的参数名，默认：limit
                },
                limits: availabePageSize,
                limit:  @Model.PageSize,
                cols: [[
                    //{ type: "checkbox", width: 50, fixed: "left" },
                    { field: 'Id', hide: true, title: 'ID' },
                    { field: '@Model.NameOf(m => m.TaskName)', title: '@Model.DisplayName(m => m.TaskName)', width: 120 },
                    {
                        field: '@Model.NameOf(m => m.GroupName)', title: '@Model.DisplayName(m => m.GroupName)', width: 120
                        , templet: function (d) {
                            var item = lodash.find(taskGroupNames, ['grpname', d.GroupName]);
                            return item === undefined ? d.GroupName : item.grpdesc;
                        }
                    },
                    { field: '@Model.NameOf(m => m.CronExpression)', title: '@Model.DisplayName(m => m.CronExpression)', width: 140 },
                    { field: '@Model.NameOf(m => m.Status)', title: '@Model.DisplayName(m => m.Status)', width: 100, align: 'center', templet: '#taskStatusTpl' },
                    { field: '@Model.NameOf(m => m.Comment)', title: '@Model.DisplayName(m => m.Comment)', width: 180 },
                    { field: '@Model.NameOf(m => m.LastStartTime)', title: '时间', minWidth: 180, templet: "#datetimeTpl" },
                    { title: '操作', width: 100, templet: '#pmsRecordMoreTpl', fixed: "right", align: "center" }
                ]],
                parseData: function (res) { //res 即为原始返回的数据
                    return {
                        "code": res.state == 200 ? 0 : -1,     //解析接口状态
                        "msg": res.state == 200 ? "" : res.message,     //解析提示文本
                        "count": res.state == 200 ? res.data.RecordsTotal : 0, //解析数据长度
                        "data": res.state == 200 ? res.data.Data : null,   //解析数据列表
                    };
                },
                skin: 'line',
                toolbar: '#pmsHeadbarTpl',
                defaultToolbar: [{
                    layEvent: 'refresh',
                    icon: 'layui-icon-refresh',
                    title: '刷新'
                }, 'filter', 'print', 'exports'],
                page: {
                    curr: 1
                },
                done: function (res) {
                    let btnItems = [];
                    var templete = $('#pmsRecordBarTpl')[0].innerHTML;
                    //David: contents inside <script id="demo" type="text/html">...</scirpt>
                    //is text string, not DOM
                    $("<div>" + templete + "</div>").find("button").each(function () {
                        let icon = $(this).find("i");
                        btnItems.push({
                            layIcon: icon.length > 0 ? icon.attr('class') : "none",
                            txt: PMSUtils.trim($(this).text()),
                            txtClass: $(this).hasClass("layui-btn-disabled") ? "layui-btn-disabled" : "",
                            event: $(this).attr("lay-event"),
                            buttonId: $(this).data("buttonid"),
                            moduleId: $(this).data("moduleid"),
                        });
                    });
                    for (var i = 0; i < res.data.length; i++) {
                        dropdown.suite("#dropdownmore_" + res.data[i].Id, {
                            align: 'center',
                            data: { dropdownBtns: btnItems },
                            template: "dropdownItemTpl"
                        });
                    }//for (var i = 0; i < res.data.length; i++) {
                } //done: function (res) {
            });

            //监听表格数据行按钮
            var triggerTaskRequest = function (paramData, rowObj) {
                const data = rowObj.data;
                http.post(backendwebapiConfig.triggerscheduletask,
                    paramData,
                    function () { //beforeSend
                        loading.Load(1, '');
                    }
                ).done(function (response) {
                    if (response.state && response.state === 200) {
                        if (response.data != null) {
                            popup.success(response.message, function () {
                                rowObj.update(response.data);
                            }, 2000);
                        }
                    }
                }).fail(function (error) {
                    http.ajax.logError(error);
                }).always(function () {
                    loading.loadRemove(500);
                    dropdown.hide("#dropdownmore_" + data.Id);
                });
            };
            table.on('tool(pms-table)', function (obj) {
                const data = obj.data;
                const $btnElem = $(this);
                const isBtnDisabled = $btnElem.hasClass("layui-btn-disabled");
                if (isBtnDisabled) return false;
                const buttonId = $btnElem.data("buttonid");
                const moduleId = $btnElem.data("moduleid");
                let paramData = {
                    ModuleId: moduleId,
                    ButtonId: buttonId,
                    Id: data.Id,
                    jobAction: 0
                };
                if (obj.event === 'OnStartTask') {
                    paramData.jobAction = 6; //see JobAction
                } else if (obj.event === 'OnPauseTask') {
                    paramData.jobAction = 4;
                } else if (obj.event === 'OnStopTask') {
                    paramData.jobAction = 5;
                } else if (obj.event === 'OnExecuteTask') {
                    paramData.jobAction = 7;
                    if (data.Status === 10) { //处于停止状态任务立即执行
                        layer.confirm('当前计划任务处于停止状态, 立即执行将启动任务, 是否继续?<br>【温馨提示】如只想单次运行任务,可在任务执行完毕后手动停止任务。',
                            { icon: 3, title: '提示' },
                            function (index) {
                                triggerTaskRequest(paramData, obj);
                                layer.close(index);
                            },
                            function () {
                                dropdown.hide("#dropdownmore_" + data.Id);
                            }
                        );
                        return false;
                    }
                } else return false;

                triggerTaskRequest(paramData, obj);
            });

            table.on('toolbar(pms-table)', function (obj) {
                if (obj.event === 'refresh') {
                    window.location.reload(true);
                }
            });

        });
    </script>

}
